\documentclass[12pt]{article}
\usepackage[cp1251]{inputenc}
\usepackage{graphicx}
\usepackage[english]{babel}



%\usepackage{cyrtext}
%\pagestyle{empty}
\textwidth160mm \textheight252mm \oddsidemargin5.5mm
\topmargin-10mm
\parskip4pt plus2pt minus2pt
%\parindent0mm
\usepackage{ifthen}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{latexsym}
\usepackage{amsthm}
\usepackage{amssymb}
\tolerance=1000 \textheight=250mm \topmargin=-20mm
\oddsidemargin=0mm \textwidth=170mm \righthyphenmin=2



\sloppy

\begin{document}
\newcommand{\pd}[2]{\frac{\partial#1}{\partial#2}}
\newcommand{\listingContent}[2]{{\bf Content of} \verb/#1/ #2}
\newcommand{\listingContenta}[2]{{\bf Content of} \verb/ {asdf}/
\begin{verbatim}
 {asdf}
\end{verbatim}}

Solutions (answers) to class (course) called "Software Engineering for SaaS" provided by Berkeley University of California (authors: Armando Fox, David Patterson).

Assignment 1. Task 1.

\begin{verbatim}
#Part 1: fun with strings. a)
def palindrome?(string)
	s = string.downcase.gsub(/\W/, "")
	s == s.reverse
end
#Part 1: fun with strings. b)
def count_words(string)
	hsh = Hash.new(0)
	a = string.downcase.split(/\b/).map{|x| x.gsub(/\W/, "")}
	a.delete("")
	a.each{|x| hsh[x] += 1 }
	hsh
end
\end{verbatim}
%\lstinputlisting[label=samplecode,caption=A sample]{sourceCode/HelloWorld.java}

Assignment 1. Task 2.
\begin{verbatim}
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def strategy_check(game)
	game.each{|x| s = x[1].downcase
	raise NoSuchStrategyError unless (s == 'r') or (s == 's')  or (s == 'p')}
	true
end
def winner(a, b)
	q = a[1].downcase
	w = b[1].downcase
	if q == w
		a
	elsif (q == 'r' and w =='s') or (q == 'p' and w == 'r') or (q == 's' and w == 'p')
		a
	else
		b
	end
end
def rps_game_winner(game)
	raise WrongNumberOfPlayersError unless game.length == 2
	strategy_check(game)
	winner(game[0], game[1])
end
def rps_tournament_winner(game)
	if game[0][0].is_a?(String)
		winner(game[0], game[1])
	else
		winner(rps_tournament_winner(game[0]), rps_tournament_winner(game[1]))
	end
end
\end{verbatim}
Assignment 1. Task 3.
\begin{verbatim}
def anagrams?(a, b)
	a.downcase.split(//).sort === b.downcase.split(//).sort
end
def combine_anagrams(words)
	b = []
	words.each do |x| 
		found = false
		if b.length === 0 
				b.push([x])
		else 
		 
				b.each do |y|
					if anagrams?(x, y[0])
						found = true
						y.push(x)
						break
					end
				end
				if !found
					b.push([x])
				end

		end
	end
	b
end
\end{verbatim}
Assignment 1. Task 4.
\begin{verbatim}
class Dessert
attr_accessor :name, :calories
def initialize(name, calories)
	@name, @calories = name, calories
end
def healthy?
	@calories < 200
end
def delicious?
	true
end
end
class JellyBean < Dessert
attr_accessor :flavor
def initialize(name, calories, flavor)
	super(name, calories)
	@flavor = flavor
end
def delicious?
	!(@flavor === "black licorice")
end
end
\end{verbatim}
Assignment 1. Task 5.
\begin{verbatim}
class Class
	def attr_accessor_with_history(attr_name)
		attr_name = attr_name.to_s  # make sure it's a string
		attr_reader attr_name  # create the attribute's getter
		attr_reader attr_name+"_history" # create bar_history getter
		class_eval %{
			def #{attr_name}=(val)
			@#{attr_name} = val
			@#{attr_name}_history = [nil] if @#{attr_name}_history.nil?
			@#{attr_name}_history.push(val)
		end
		}
  end
end
class Foo
	attr_accessor_with_history :bar
end
\end{verbatim}
Assignment 2. Task 1.
\begin{verbatim}
class Numeric
  @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar'=> 1}
  def method_missing(method_id, *arguments, &block)
    singular_currency = method_id.to_s.gsub( /s$/, '')
    if @@currencies.has_key?(singular_currency)
      self * @@currencies[singular_currency]
    elsif method_id.to_s == 'in'
	curr = arguments.first.to_s.gsub( /s$/, '')
	if @@currencies.has_key?(curr)
	 self / @@currencies[curr]
	else
      self # maybe need correction
    end
	else
      super
    end
  end
end

class String
  def palindrome?
	s = self.downcase.gsub(/\W/, "")
	s == s.reverse
  end
end

module Enumerable
  def palindrome?
	s = self.to_a
	s == s.reverse
  end
end
\end{verbatim}
Assignment 2. Task 2.
\begin{verbatim}
class CartesianProduct
  include Enumerable
  attr_accessor :res
  def initialize(a, b)
	@res = []
	a.each {|x| b.each {|y| @res.push([x, y])}}
	@res
  end
  def each
      for i in 0...@res.length
		yield @res[i]
      end
  end
end
\end{verbatim}
Assignment 2. Task 3-5.

For completion tasks 3-5 you can use any link of working correctly solutions provided by other users like
\begin{verbatim}
http://electric-snow-3627.heroku.com/movies/
\end{verbatim}
or you can download solution from here:
\begin{verbatim}
https://github.com/Patlatus/hw3_rottenpotatoes
\end{verbatim}

Assignment 3. Submitting of features folder was needed.

{\bf Content of} \verb/sort_movie_list.feature/
\begin{verbatim}
Feature: display list of movies sorted by different criteria
 
  As an avid moviegoer
  So that I can quickly browse movies based on my preferences
  I want to see movies sorted by title or release date

Background: movies have been added to database
  
  Given the following movies exist:
  | title                   | rating | release_date |
  | Aladdin                 | G      | 25-Nov-1992  |
  | The Terminator          | R      | 26-Oct-1984  |
  | When Harry Met Sally    | R      | 21-Jul-1989  |
  | The Help                | PG-13  | 10-Aug-2011  |
  | Chocolat                | PG-13  | 5-Jan-2001   |
  | Amelie                  | R      | 25-Apr-2001  |
  | 2001: A Space Odyssey   | G      | 6-Apr-1968   |
  | The Incredibles         | PG     | 5-Nov-2004   |
  | Raiders of the Lost Ark | PG     | 12-Jun-1981  |
  | Chicken Run             | G      | 21-Jun-2000  |

  And I am on the RottenPotatoes home page

Scenario: sort movies alphabetically
  When I check all ratings
  And I click 'title' header
  Then I should see "2001: A Space Odyssey" before "Aladdin"
  And I should see "Aladdin" before "Amelie"
  And I should see "Amelie" before "Chicken Run"
  And I should see "Chicken Run" before "Chocolat"
  And I should see "Chocolat" before "Raiders of the Lost Ark"
  And I should see "Raiders of the Lost Ark" before "The Help"
  And I should see "The Help" before "The Incredibles"
  And I should see "The Incredibles" before "The Terminator"
  And I should see "The Terminator" before "When Harry Met Sally"

Scenario: sort movies in increasing order of release date
  When I check all ratings
  And I click 'release_date' header
  Then I should see "2001: A Space Odyssey" before "Raiders of the Lost Ark"
  And I should see "Raiders of the Lost Ark" before "The Terminator"
  And I should see "The Terminator" before "When Harry Met Sally"
  And I should see "When Harry Met Sally" before "Aladdin"    
  And I should see "Aladdin" before "Chicken Run"
  And I should see "Chicken Run" before "Chocolat"
  And I should see "Amelie" before "The Incredibles"
  And I should see "Chocolat" before "Amelie"
  And I should see "Amelie" before "The Help"
\end{verbatim}

{\bf Content of} \verb/filter_movie_list.feature/
\begin{verbatim}
Feature: display list of movies filtered by MPAA rating
 
  As a concerned parent
  So that I can quickly browse movies appropriate for my family
  I want to see movies matching only certain MPAA ratings

Background: movies have been added to database

  Given the following movies exist:
  | title                   | rating | release_date |
  | Aladdin                 | G      | 25-Nov-1992  |
  | The Terminator          | R      | 26-Oct-1984  |
  | When Harry Met Sally    | R      | 21-Jul-1989  |
  | The Help                | PG-13  | 10-Aug-2011  |
  | Chocolat                | PG-13  | 5-Jan-2001   |
  | Amelie                  | R      | 25-Apr-2001  |
  | 2001: A Space Odyssey   | G      | 6-Apr-1968   |
  | The Incredibles         | PG     | 5-Nov-2004   |
  | Raiders of the Lost Ark | PG     | 12-Jun-1981  |
  | Chicken Run             | G      | 21-Jun-2000  |

  And  I am on the RottenPotatoes home page
  
Scenario: restrict to movies with 'PG' or 'R' ratings
  # enter step(s) to check the 'PG' and 'R' checkboxes
  When I check the following ratings: PG,R
  # enter step(s) to uncheck all other checkboxes
  And I uncheck the following ratings: G,PG-13
  # enter step to "submit" the search form on the homepage
  And I press the "Refresh" button
  # enter step(s) to ensure that PG and R movies are visible
  Then I should see the following ratings: PG,R
  # enter step(s) to ensure that other movies are not visible
  And I should not see the following ratings: G,PG-13

Scenario: no ratings selected
  Given I uncheck all ratings
  And I press "Refresh"
  Then I should see no movies
 
Scenario: all ratings selected
  When I check all ratings
  And I press "Refresh"
  Then I should see all of the movies
\end{verbatim}
{\bf Content of} \verb/step_definitions\movie_steps.rb/
\begin{verbatim}
# Add a declarative step here for populating the DB with movies.

Given /the following movies exist/ do |movies_table|
  movies_table.hashes.each do |movie|
    Movie.find_or_create_by_title(:title => movie["title"], :rating => movie["rating"], :release_date => movie["release_date"])
  end
  assert movies_table.hashes.size == Movie.all.count
end

# Make sure that one string (regexp) occurs before or after another one
#   on the same page

Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
  titles = page.all("table#movies tbody tr td[1]").map {|t| t.text}
  assert titles.index(e1) < titles.index(e2)
end

When /I (un)?check the following ratings: (.*)/ do |uncheck, rating_list|
  rating_list.split(",").each do |field|
    field = field.strip
    if uncheck == "un"
       step %Q{I uncheck "ratings_#{field}"}
       step %Q{the "ratings_#{field}" checkbox should not be checked}
    else
      step %Q{I check "ratings_#{field}"}
      step %Q{the "ratings_#{field}" checkbox should be checked}
    end
  end
end
 
Then /^I should see the following ratings: (.*)/ do |rating_list|
  ratings = page.all("table#movies tbody tr td[2]").map! {|t| t.text}
  rating_list.split(",").each do |field|
    assert ratings.include?(field.strip)
  end
end
 
Then /^I should not see the following ratings: (.*)/ do |rating_list|
  ratings = page.all("table#movies tbody tr td[2]").map! {|t| t.text}
  rating_list.split(",").each do |field|
    assert !ratings.include?(field.strip)
  end
end
 
Then /^I should see all of the movies$/ do
  rows = page.all("table#movies tbody tr td[1]").map! {|t| t.text}
  assert ( rows.size == Movie.all.count )
end
 
When /^(?:|I )press the "([^"]*)" button/ do |button|
  click_button(button)
end

Then /^I should see no movies$/ do
  rows = page.all("table#movies tbody tr td[1]").map! {|t| t.text}
  assert rows.size == 0
end

When /I (un)?check all ratings/ do |unchecked|
  page.all("form input[type='checkbox']").each do |rating_checkbox|
    if unchecked
      page.uncheck rating_checkbox[:name]
    else
      page.check rating_checkbox[:name]
    end
  end
end

When /^I click 'title' header$/ do
  #pending # express the regexp above with the code you wish you had
  click_link('title_header')
end

Then /^I should see movies sorted alphabetically$/ do
  #pending # express the regexp above with the code you wish you had
  assert movies == Movie.all.sort_by {|hash| hash[:title]}
end

When /^I click 'release_date' header$/ do
  #pending # express the regexp above with the code you wish you had
    click_link('release_date_header')
end

Then /^I should see movies sorted in increasing order of release date$/ do
  #pending # express the regexp above with the code you wish you had
  assert movies == Movie.all.sort_by {|hash| hash[:release_date]}
end
\end{verbatim}
{\bf Content of} \verb/step_definitions\web_steps.rb/
\begin{verbatim}
require 'uri'
require 'cgi'
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths"))
require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "selectors"))

module WithinHelpers
  def with_scope(locator)
    locator ? within(*selector_for(locator)) { yield } : yield
  end
end
World(WithinHelpers)

# Single-line step scoper
When /^(.*) within (.*[^:])$/ do |step, parent|
  with_scope(parent) { When step }
end

# Multi-line step scoper
When /^(.*) within (.*[^:]):$/ do |step, parent, table_or_string|
  with_scope(parent) { When "#{step}:", table_or_string }
end

Given /^(?:|I )am on (.+)$/ do |page_name|
  visit path_to(page_name)
end

When /^(?:|I )go to (.+)$/ do |page_name|
  visit path_to(page_name)
end

When /^(?:|I )press "([^"]*)"$/ do |button|
  click_button(button)
end

When /^(?:|I )follow "([^"]*)"$/ do |link|
  click_link(link)
end

When /^(?:|I )fill in "([^"]*)" with "([^"]*)"$/ do |field, value|
  fill_in(field, :with => value)
end

When /^(?:|I )fill in "([^"]*)" for "([^"]*)"$/ do |value, field|
  fill_in(field, :with => value)
end

# Use this to fill in an entire form with data from a table. Example:
#
#   When I fill in the following:
#     | Account Number | 5002       |
#     | Expiry date    | 2009-11-01 |
#     | Note           | Nice guy   |
#     | Wants Email?   |            |
#
# TODO: Add support for checkbox, select or option
# based on naming conventions.
#
When /^(?:|I )fill in the following:$/ do |fields|
  fields.rows_hash.each do |name, value|
    When %{I fill in "#{name}" with "#{value}"}
  end
end

When /^(?:|I )select "([^"]*)" from "([^"]*)"$/ do |value, field|
  select(value, :from => field)
end

When /^(?:|I )check "([^"]*)"$/ do |field|
  check(field)
end

When /^(?:|I )uncheck "([^"]*)"$/ do |field|
  uncheck(field)
end

When /^(?:|I )choose "([^"]*)"$/ do |field|
  choose(field)
end

When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"$/ do |path, field|
  attach_file(field, File.expand_path(path))
end

Then /^(?:|I )should see "([^"]*)"$/ do |text|
  if page.respond_to? :should
    page.should have_content(text)
  else
    assert page.has_content?(text)
  end
end

Then /^(?:|I )should see \/([^\/]*)\/$/ do |regexp|
  regexp = Regexp.new(regexp)

  if page.respond_to? :should
    page.should have_xpath('//*', :text => regexp)
  else
    assert page.has_xpath?('//*', :text => regexp)
  end
end

Then /^(?:|I )should not see "([^"]*)"$/ do |text|
  if page.respond_to? :should
    page.should have_no_content(text)
  else
    assert page.has_no_content?(text)
  end
end

Then /^(?:|I )should not see \/([^\/]*)\/$/ do |regexp|
  regexp = Regexp.new(regexp)

  if page.respond_to? :should
    page.should have_no_xpath('//*', :text => regexp)
  else
    assert page.has_no_xpath?('//*', :text => regexp)
  end
end

Then /^the "([^"]*)" field(?: within (.*))? should contain "([^"]*)"$/ do |field, parent, value|
  with_scope(parent) do
    field = find_field(field)
    field_value = (field.tag_name == 'textarea') ? field.text : field.value
    if field_value.respond_to? :should
      field_value.should =~ /#{value}/
    else
      assert_match(/#{value}/, field_value)
    end
  end
end

Then /^the "([^"]*)" field(?: within (.*))? should not contain "([^"]*)"$/ do |field, parent, value|
  with_scope(parent) do
    field = find_field(field)
    field_value = (field.tag_name == 'textarea') ? field.text : field.value
    if field_value.respond_to? :should_not
      field_value.should_not =~ /#{value}/
    else
      assert_no_match(/#{value}/, field_value)
    end
  end
end

Then /^the "([^"]*)" field should have the error "([^"]*)"$/ do |field, error_message|
  element = find_field(field)
  classes = element.find(:xpath, '..')[:class].split(' ')

  form_for_input = element.find(:xpath, 'ancestor::form[1]')
  using_formtastic = form_for_input[:class].include?('formtastic')
  error_class = using_formtastic ? 'error' : 'field_with_errors'

  if classes.respond_to? :should
    classes.should include(error_class)
  else
    assert classes.include?(error_class)
  end

  if page.respond_to?(:should)
    if using_formtastic
      error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]')
      error_paragraph.should have_content(error_message)
    else
      page.should have_content("#{field.titlecase} #{error_message}")
    end
  else
    if using_formtastic
      error_paragraph = element.find(:xpath, '../*[@class="inline-errors"][1]')
      assert error_paragraph.has_content?(error_message)
    else
      assert page.has_content?("#{field.titlecase} #{error_message}")
    end
  end
end

Then /^the "([^"]*)" field should have no error$/ do |field|
  element = find_field(field)
  classes = element.find(:xpath, '..')[:class].split(' ')
  if classes.respond_to? :should
    classes.should_not include('field_with_errors')
    classes.should_not include('error')
  else
    assert !classes.include?('field_with_errors')
    assert !classes.include?('error')
  end
end

Then /^the "([^"]*)" checkbox(?: within (.*))? should be checked$/ do |label, parent|
  with_scope(parent) do
    field_checked = find_field(label)['checked']
    if field_checked.respond_to? :should
      field_checked.should be_true
    else
      assert field_checked
    end
  end
end

Then /^the "([^"]*)" checkbox(?: within (.*))? should not be checked$/ do |label, parent|
  with_scope(parent) do
    field_checked = find_field(label)['checked']
    if field_checked.respond_to? :should
      field_checked.should be_false
    else
      assert !field_checked
    end
  end
end
 
Then /^(?:|I )should be on (.+)$/ do |page_name|
  current_path = URI.parse(current_url).path
  if current_path.respond_to? :should
    current_path.should == path_to(page_name)
  else
    assert_equal path_to(page_name), current_path
  end
end

Then /^(?:|I )should have the following query string:$/ do |expected_pairs|
  query = URI.parse(current_url).query
  actual_params = query ? CGI.parse(query) : {}
  expected_params = {}
  expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} 
  
  if actual_params.respond_to? :should
    actual_params.should == expected_params
  else
    assert_equal expected_params, actual_params
  end
end

Then /^show me the page$/ do
  save_and_open_page
end
\end{verbatim}
{\bf Content of} \verb/support\env.rb/
\begin{verbatim}
require 'cucumber/rails'

Capybara.default_selector = :css

ActionController::Base.allow_rescue = false

begin
  DatabaseCleaner.strategy = :transaction
rescue NameError
  raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it."
end

Cucumber::Rails::Database.javascript_strategy = :truncation
\end{verbatim}
{\bf Content of} \verb/support\paths.rb/
\begin{verbatim}
module NavigationHelpers

  def path_to(page_name)
    case page_name

    when /^the home\s?page$/
      '/'
    when /^the RottenPotatoes home page$/
      '/movies'
    when /^the Create New Movie page$/
      '/movies/new'
    else
      begin
        page_name =~ /^the (.*) page$/
        path_components = $1.split(/\s+/)
        self.send(path_components.push('path').join('_').to_sym)
      rescue NoMethodError, ArgumentError
        raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
          "Now, go and add a mapping in #{__FILE__}"
      end
    end
  end
end

World(NavigationHelpers)
\end{verbatim}
{\bf Content of} \verb/support\selectors.rb/
\begin{verbatim}
module HtmlSelectorsHelpers

  def selector_for(locator)
    case locator

    when "the page"
      "html > body"

    when /^"(.+)"$/
      $1

    else
      raise "Can't find mapping from \"#{locator}\" to a selector.\n" +
        "Now, go and add a mapping in #{__FILE__}"
    end
  end
end

World(HtmlSelectorsHelpers)

\end{verbatim}
%{\bf Content of} \verb/sort_movie_list.feature/
%\begin{verbatim}
%\end{verbatim}
%\listingContent ab{awdf}{zxcvzxcv}
\end{document}
